import re
from docx.oxml.text.paragraph import CT_P
from docx.oxml.table import CT_Tbl

from docx.text.paragraph import Paragraph
from docx.table import Table

from docx import Document

import json
fangan1 = {}
with open("dagang5.json", encoding='UTF-8') as f:
    fangan1 = json.load(f)


def find(pattern, pt):
    def _find_keyword(pattern, pt):
        if pattern:
            if isinstance(pt, Paragraph):
                g = re.search(pattern=pattern, string=pt.text)
                if g:
                    for v in g.groupdict().values():
                        return v
                    return ''
        return None

    if isinstance(pattern, str):
        return _find_keyword(pattern, pt)
    elif isinstance(pattern, list):
        for ep in pattern:
            value = _find_keyword(ep, pt)
            if value != None:
                return value
    return None


def find_set_value(pattern, attrname, content):
    # print(self.content)
    for pt in content.content:
        value = find(pattern, pt)
        if value != None:
            if hasattr(content, attrname):
                setattr(content, attrname, value)
                print(attrname, '=', [value])
            else:
                print('需要先定义属性 '*10)
            return value
    return None


class Content(object):
    def __init__(self):
        super().__init__()
        self.content = []
        self.line = -1

    def append(self, content):
        self.content.append(content)

    def __str__(self):
        return "共%s行" % len(self.content)


class Dagang(Content):
    __slots__ = ("大纲标题", "课程编码")

    def __init__(self):
        super().__init__()
        self.大纲标题 = ''
        self.课程编码 = ''

    def __str__(self):
        return super().__str__()

    def read(self):

        find_set_value(fangan1['dagang']['大纲标题'], '大纲标题', self)
        find_set_value(fangan1['dagang']['课程编码'], '课程编码', self)
        for line, b1 in enumerate(self.content):
            self.line = line

        print(self, *["%s=[%s]" % (slot,  getattr(self, slot))
                      for slot in self.__slots__])

    def split(self):
        pass


class DagangRead(Content):

    def __init__(self, filename, *args, **kwargs):
        self.doc = Document(filename)
        self.read()

    def read(self, filename=''):
        if filename:
            self.doc = Document(filename)
        self.content = self.readcontent()
        self.line = -1
        self.daganglist = self.split()
        for dagang in self.daganglist:
            dagang.read()
        # print(*self.daganglist)

    def split(self):
        dagang = None
        daganglist = []
        for line, b1 in enumerate(self.content):
            self.line = line
            value = find(fangan1['new'], b1)
            if value != None:
                if len(daganglist) > 3:
                    break
                dagang = Dagang()
                daganglist.append(dagang)
            if dagang != None:
                dagang.append(b1)
        return daganglist

    def readcontent(self):
        content = []
        body = self.doc.element.body
        for line, b1 in enumerate(body.iterchildren()):
            if isinstance(b1, CT_P):
                content.append(Paragraph(b1, body))
            elif isinstance(b1, CT_Tbl):
                content.append(Table(b1, body))
            else:
                print(line, '未处理类型 '*5, type(b1))
        return content


if __name__ == "__main__":
    DagangRead(r"d:\\专业选修课.docx")
